<?php

namespace app\service;

use app\model\Room;
use app\model\AccountingRecord;
use app\model\RoomUser;

class TeaMealService
{
    /**
     * 自动扣除茶饭费
     * 当玩家赢分时，自动从赢分中扣除茶饭费
     */
    public static function autoDeductTeaMeal($roomId, $userId, $winAmount)
    {
        try {
            // 获取房间的茶饭设置
            $room = Room::find($roomId);
            if (!$room || $room->tea_meal_limit <= 0) {
                return [
                    'deducted' => false,
                    'amount' => 0,
                    'reason' => '房间未设置茶饭费规则'
                ];
            }

            // 检查茶饭费模式设置
            if ($room->tea_meal_mode === 'percentage' && $room->tea_meal_percentage <= 0) {
                return [
                    'deducted' => false,
                    'amount' => 0,
                    'reason' => '按比例模式未设置扣除比例'
                ];
            }

            if ($room->tea_meal_mode === 'fixed' && $room->tea_meal_fixed_amount <= 0) {
                return [
                    'deducted' => false,
                    'amount' => 0,
                    'reason' => '固定分数模式未设置固定金额'
                ];
            }

            // 获取用户已支付的茶饭费总额
            $paidTeaMeal = AccountingRecord::where('room_id', $roomId)
                ->where('user_id', $userId)
                ->where('type', 'tea_meal')
                ->where('score', '<', 0) // 负数表示支付
                ->sum('score');

            $paidTeaMeal = abs($paidTeaMeal); // 转为正数

            // 检查是否已达到上限
            if ($paidTeaMeal >= $room->tea_meal_limit) {
                return [
                    'deducted' => false,
                    'amount' => 0,
                    'reason' => '已达到茶饭费上限'
                ];
            }

            // 根据模式计算本次应扣除的茶饭费
            if ($room->tea_meal_mode === 'percentage') {
                $shouldDeduct = $winAmount * ($room->tea_meal_percentage / 100);
            } else {
                // 固定分数模式：每次赢分扣除固定分数
                $shouldDeduct = $room->tea_meal_fixed_amount;
            }
            
            // 确保不超过剩余上限
            $remainingLimit = $room->tea_meal_limit - $paidTeaMeal;
            $actualDeduct = min($shouldDeduct, $remainingLimit);

            if ($actualDeduct <= 0) {
                return [
                    'deducted' => false,
                    'amount' => 0,
                    'reason' => '无需扣除茶饭费'
                ];
            }

            // 创建茶饭费记录
            // 先计算模式文本，避免在字符串中直接使用 === 运算符
            $modeText = $room->tea_meal_mode === 'percentage' ? '按比例' : '固定分数';
            $teaMealRecord = AccountingRecord::createRecord([
                'room_id' => $roomId,
                'user_id' => $userId,
                'target_user_id' => 0, // 0表示系统扣除
                'score' => -$actualDeduct, // 负数表示用户支付
                'description' => "自动扣除茶饭费（{$modeText}模式，扣除{$actualDeduct}分）",
                'type' => 'tea_meal',
                'is_settled' => 0
            ]);

            // 更新用户分数
            self::updateRoomUserScore($roomId, $userId, -$actualDeduct);

            return [
                'deducted' => true,
                'amount' => $actualDeduct,
                'reason' => "自动扣除茶饭费",
                'record_id' => $teaMealRecord->id,
                'remaining_limit' => $remainingLimit - $actualDeduct
            ];

        } catch (\Exception $e) {
            error_log('自动扣除茶饭费失败: ' . $e->getMessage());
            return [
                'deducted' => false,
                'amount' => 0,
                'reason' => '扣除失败: ' . $e->getMessage()
            ];
        }
    }

    /**
     * 获取用户的茶饭费统计
     */
    public static function getUserTeaMealStats($roomId, $userId)
    {
        try {
            $room = Room::find($roomId);
            if (!$room) {
                return null;
            }

            // 获取用户已支付的茶饭费
            $paidTeaMeal = AccountingRecord::where('room_id', $roomId)
                ->where('user_id', $userId)
                ->where('type', 'tea_meal')
                ->where('score', '<', 0)
                ->sum('score');

            $paidTeaMeal = abs($paidTeaMeal);

            return [
                'room_limit' => $room->tea_meal_limit,
                'room_percentage' => $room->tea_meal_percentage,
                'paid_amount' => $paidTeaMeal,
                'remaining_limit' => max(0, $room->tea_meal_limit - $paidTeaMeal),
                'is_limit_reached' => $paidTeaMeal >= $room->tea_meal_limit
            ];

        } catch (\Exception $e) {
            error_log('获取茶饭费统计失败: ' . $e->getMessage());
            return null;
        }
    }

    /**
     * 获取房间所有用户的茶饭费统计
     */
    public static function getRoomTeaMealStats($roomId)
    {
        try {
            $room = Room::find($roomId);
            if (!$room) {
                return null;
            }

            // 获取房间内所有用户
            $roomUsers = RoomUser::where('room_id', $roomId)
                ->where('status', 'active')
                ->with('user')
                ->get();

            $stats = [];
            foreach ($roomUsers as $roomUser) {
                $userStats = self::getUserTeaMealStats($roomId, $roomUser->user_id);
                if ($userStats) {
                    $stats[] = [
                        'user_id' => $roomUser->user_id,
                        'user_nickname' => $roomUser->user->nickname ?? '未知用户',
                        'user_avatar' => $roomUser->user->avatar ?? '',
                        'paid_amount' => $userStats['paid_amount'],
                        'remaining_limit' => $userStats['remaining_limit'],
                        'is_limit_reached' => $userStats['is_limit_reached']
                    ];
                }
            }

            return [
                'room_limit' => $room->tea_meal_limit,
                'room_percentage' => $room->tea_meal_percentage,
                'room_mode' => $room->tea_meal_mode,
                'room_fixed_amount' => $room->tea_meal_fixed_amount,
                'users' => $stats,
                'total_paid' => array_sum(array_column($stats, 'paid_amount'))
            ];

        } catch (\Exception $e) {
            error_log('获取房间茶饭费统计失败: ' . $e->getMessage());
            return null;
        }
    }

    /**
     * 更新房间用户分数
     */
    private static function updateRoomUserScore($roomId, $userId, $scoreChange)
    {
        try {
            $roomUser = RoomUser::where('room_id', $roomId)
                ->where('user_id', $userId)
                ->first();

            if ($roomUser) {
                $roomUser->current_score += $scoreChange;
                $roomUser->save();
            }
        } catch (\Exception $e) {
            error_log('更新房间用户分数失败: ' . $e->getMessage());
        }
    }

    /**
     * 检查是否应该扣除茶饭费
     */
    public static function shouldDeductTeaMeal($roomId, $userId, $winAmount)
    {
        try {
            $room = Room::find($roomId);
            if (!$room || $room->tea_meal_limit <= 0 || $room->tea_meal_percentage <= 0) {
                return false;
            }

            // 获取用户已支付的茶饭费
            $paidTeaMeal = AccountingRecord::where('room_id', $roomId)
                ->where('user_id', $userId)
                ->where('type', 'tea_meal')
                ->where('score', '<', 0)
                ->sum('score');

            $paidTeaMeal = abs($paidTeaMeal);

            // 检查是否已达到上限
            if ($paidTeaMeal >= $room->tea_meal_limit) {
                return false;
            }

            // 检查是否有赢分
            if ($winAmount <= 0) {
                return false;
            }

            return true;

        } catch (\Exception $e) {
            error_log('检查茶饭费扣除条件失败: ' . $e->getMessage());
            return false;
        }
    }
}
